package spring.captcha.demo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.lang.Console;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import spring.captcha.demo.model.Captcha;
import spring.captcha.demo.model.Student;

import java.io.IOException;
import java.net.http.HttpResponse;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    public Captcha captcha;
    public Long Timeout = 3*60*1000l;

    @RequestMapping("/getcaptcha")
    public void getCaptcha(HttpServletResponse response , HttpSession session){
        response.setContentType("image/jpeg");
        response.setHeader("Progma","No-cache");
        try {
            //定义图形验证码的长和宽
            ShearCaptcha captchamodel = CaptchaUtil.createShearCaptcha(captcha.getWidth(), captcha.getHeight());
            //captcha.write("d:/line.png");
            String string = captchamodel.getCode();
            session.setAttribute(captcha.getSession().getKey(),string);
//            captchamodel.verify("1334");
            session.setAttribute(captcha.getSession().getDate(),System.currentTimeMillis());
            captchamodel.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/cheak")
    public boolean cheakCaptcha(HttpSession session,String captchacode){
        if(!StringUtils.hasLength(captchacode)){
            return false;
        }
        String cheakstring  = (String)session.getAttribute(captcha.getSession().getKey());
        String val = cheakstring.toLowerCase();
        System.out.println(val);
        if(captchacode.equals(val) && session.getAttribute(captcha.getSession().getDate())!=null && System.currentTimeMillis()-(long)session.getAttribute(captcha.getSession().getDate())<=Timeout){
            return true;
        }
        return false;
    }

}
